package com.stylefeng.guns.modular.data.controller;

import cn.afterturn.easypoi.entity.vo.NormalExcelConstants;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import cn.afterturn.easypoi.exception.excel.ExcelImportException;
import com.baomidou.mybatisplus.plugins.Page;
import com.stylefeng.guns.common.constant.factory.PageFactory;
import com.stylefeng.guns.common.persistence.model.ResourceData;
import com.stylefeng.guns.common.plugin.entity.ResponseMsg;
import com.stylefeng.guns.common.plugin.excel.MyExcelImportUtil;
import com.stylefeng.guns.core.base.controller.BaseController;
import com.stylefeng.guns.core.support.BeanKit;
import com.stylefeng.guns.modular.data.dao.ResourceDataDao;
import com.stylefeng.guns.modular.data.service.IResourceDataService;
import com.stylefeng.guns.modular.data.transfer.ResourceDataXlsM;
import com.stylefeng.guns.modular.data.transfer.ResourceDataXlsVerifyHandler;
import com.stylefeng.guns.modular.data.transfer.ThirdLvIndicationXlsM;
import com.stylefeng.guns.modular.data.warpper.ResourceDataWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 源数据控制器
 *
 * @author xuziyang
 * @Date 2018-01-17 11:24:43
 */
@Controller
@RequestMapping("/resourceData")
@Slf4j
public class ResourceDataController extends BaseController {

    private String PREFIX = "/data/resourceData/";

    @Autowired
    private IResourceDataService resourceDataService;

    @Autowired
    private ResourceDataDao resourceDataDao;

    /**
     * 跳转到源数据首页
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "resourceData.html";
    }

    /**
     * 跳转到添加源数据
     */
    @RequestMapping("/resourceData_add")
    public String resourceDataAdd() {
        return PREFIX + "resourceData_add.html";
    }

    /**
     * 跳转到修改源数据
     */
    @RequestMapping("/resourceData_update/{resourceDataId}")
    public String resourceDataUpdate(@PathVariable Integer resourceDataId, Model model) {
        ResourceData resourceData = resourceDataService.selectById(resourceDataId);
        Map<String, Object> map = BeanKit.beanToMap(resourceData);
        model.addAttribute("item", new ResourceDataWrapper(map).warp());
        return PREFIX + "resourceData_edit.html";
    }

    /**
     * 获取源数据列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(@RequestParam(required = false) String startTime,
                       @RequestParam(required = false) String endTime,
                       @RequestParam(required = false) String resourceDataTypeName,
                       @RequestParam(required = false) String roadnetName) {
        Page<ResourceData> page = new PageFactory<ResourceData>().defaultPage();
        List<Map<String, Object>> list = resourceDataDao.selectPage(page, startTime, endTime, resourceDataTypeName, roadnetName);
        page.setRecords((List<ResourceData>) new ResourceDataWrapper(list).warp());
        return super.packForBT(page);
    }

    /**
     * 新增源数据
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    public Object add(ResourceData resourceData) {
        resourceDataService.insert(resourceData);
        return super.SUCCESS_TIP;
    }

    /**
     * 删除源数据
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public Object delete(@RequestParam Integer resourceDataId) {
        resourceDataService.deleteById(resourceDataId);
        return SUCCESS_TIP;
    }

    /**
     * 清空源数据
     *
     * @return
     */
    @RequestMapping(value = "/delete/all")
    @ResponseBody
    public Object deleteAll() {
        resourceDataService.delete(null);
        return SUCCESS_TIP;
    }


    /**
     * 修改源数据
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    public Object update(ResourceData resourceData) {
        resourceDataService.updateById(resourceData);
        return super.SUCCESS_TIP;
    }

    /**
     * 源数据详情
     */
    @RequestMapping(value = "/detail/{resourceDataId}")
    @ResponseBody
    public Object detail(@PathVariable("resourceDataId") Integer resourceDataId) {
        return resourceDataService.selectById(resourceDataId);
    }

    /**
     * 导出excel 使模板
     */
    @RequestMapping(value = "/exportXlsByT", headers = {"Accept=application/vnd.ms-excel"})
    public String exportXlsByT(@RequestParam(value = "pids") Integer pids, ModelMap modelMap) {
        String sheetName = "";
        if (pids == 1) {
            sheetName = "车站";
        } else if (pids == 5) {
            sheetName = "线路";
        } else if (pids == 9) {
            sheetName = "区域中心";
        } else if (pids == 43) {
            sheetName = "路网";
        }

        modelMap.put(NormalExcelConstants.FILE_NAME, sheetName + "源数据");
        modelMap.put(NormalExcelConstants.CLASS, ThirdLvIndicationXlsM.class);
        modelMap.put(NormalExcelConstants.PARAMS, new ExportParams(sheetName,
                "注意：1:出站口为选填项; 2:源数据中的值必须为数字，请去掉相关单位; 3:时间格式为：'2018/01/01 12:00:00'; 4:请阅读每个数据后的说明",
                sheetName));
        modelMap.put(NormalExcelConstants.DATA_LIST, resourceDataService.selectThirdLVIndicationXlsMList(pids));
        return NormalExcelConstants.EASYPOI_EXCEL_VIEW;
    }


    @RequestMapping(method = RequestMethod.POST, path = "/importExcel")
    @ResponseBody
    public ResponseMsg importExcel(MultipartHttpServletRequest multipartRequest, HttpServletResponse response, ModelMap modelMap) throws Exception {
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setNeedVerfiy(true);
            params.setTitleRows(3);
            params.setHeadRows(1);
            params.setKeyIndex(1);
            //是否需要保存上传的Excel
            params.setNeedSave(false);
            params.setVerifyHandler(new ResourceDataXlsVerifyHandler());
			try {
				ExcelImportResult<ResourceDataXlsM> result = MyExcelImportUtil
						.importExcelMore(file.getInputStream(), ResourceDataXlsM.class, params);
				if (result.isVerfiyFail()) {
					String fileName = saveFailExcel(result.getFailWorkbook(),file);
					return new ResponseMsg(422, fileName);
				}
				resourceDataService.insertDtoBatch(result.getList());
				file.getInputStream().close();
			}catch (ExcelImportException e){
				return new ResponseMsg(500,"上传失败，请检查你的时间格式");
			}
        }
        return new ResponseMsg(200,"上传成功");
    }

	private String saveFailExcel(Workbook workbook, MultipartFile file) {

		FileOutputStream fos = null;
		try {
			String randomFileName = UUID.randomUUID().toString() + "." + getFileSuffix(file);
			String filePath = System.getProperty("java.io.tmpdir") + randomFileName;
			fos = new FileOutputStream(filePath);
			workbook.write(fos);
			return randomFileName;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			if(fos != null){
				try {
					fos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return null;
	}

	private String getFileSuffix(MultipartFile file) {
		String fileName = file.getOriginalFilename();
		String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
		return suffix;
	}
}
